﻿using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Security.Policy;
using Fetches.Fetch.Dto;
using Fetches.Process.Utility;
using Newtonsoft.Json;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;

namespace Fetches.Process.Pipelines
{
    [Table("ResultItems")]
    internal class MySqlResultItem
    {
        public MySqlResultItem(ResultItems result)
        {
            Code = result.Request.Hash;
            Url = result.Request.Url.OriginalString;
            Data = JsonConvert.SerializeObject(result.Data);
        }

        public string Code { get; set; }

        public string Url { get; set; }
        [StringLength(StringLengthAttribute.MaxText)]
        public string Data { get; set; }

    }

    public class MySqlPipeline : AbstractPipeline
    {
        private ConnectionPool _pool;

        protected override void OnInitial(string site)
        {
            _pool = ConnectionPool.GetInstance(typeof(Site).Name);
            _pool.GetConnection().CreateTableIfNotExists<MySqlResultItem>();
        }

        protected override void OnProcess(string site, ResultItems result)
        {
            var conn = _pool.GetConnection();
            try
            {
                var item = new MySqlResultItem(result);
                if (!conn.Exists<MySqlResultItem>(i => i.Code == item.Code))
                {
                    conn.Insert(item);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                _pool.ReturnConnection(conn);
            }
        }

    }
}